<template>
  <div>
    <el-upload v-show="false" class="avatar-uploader quill-img" :show-upload-list="false" :on-success="uploadSuccess" :http-request="handleUploadForm"
      :before-upload="beforeUpload" :format="['jpg', 'jpeg', 'png', 'gif']" :max-size="2048" multiple :action="$config.SERVER_URL + '/file/upload'">
      <!-- <Button icon="ios-cloud-upload-outline" ></Button> -->
    </el-upload>
    <el-card class="card" :style="{ height: Number(height) * heightMultiple + 'px' }">
      <quill-editor class="quill-editor ql-editor" @focus="onEditorFocus($event)" @blur="getTxtchild" @input="getTxtchild" v-model="content" :ref="toref"
        :style="{ height: height + 'px' }" :options="editorOption">
      </quill-editor>
    </el-card>

    <!--视频上传弹窗-->
    <div>
      <el-dialog :close-on-click-modal="false" width="50%" style="margin-top: 1px" title="视频上传" :visible.sync="videoForm.show" append-to-body>
        <el-tabs v-model="videoForm.activeName">
          <!-- <el-tab-pane label="添加视频链接" name="first">
            <el-input v-model="videoForm.videoLink" placeholder="请输入视频链接" clearable></el-input>
            <el-button type="primary" size="small" style="margin: 20px 0px 0px 0px " @click="insertVideoLink(videoForm.videoLink, '')">确认
            </el-button>
          </el-tab-pane> -->
          <el-tab-pane label="本地视频上传" name="second">
            <el-upload v-loading="loading" style="text-align: center;" drag :http-request="handleUploadVideoForm" :action="uploadVideoConfig.uploadUrl"
              accept="video/*" :name="uploadVideoConfig.name" :before-upload="onBeforeUploadVideo" :on-success="onSuccessVideo" :on-error="onErrorVideo"
              :multiple="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传MP4文件，且不超过{{ uploadVideoConfig.maxSize }}M</div>
            </el-upload>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
  </div>
</template>

<script>
/**
 * 一个页面使用多个富文本编辑器时：（只使用一个的时候可以不传）
 * quillIndex:当前选择上传图片的dom节点的标识，默认是：0
 * toref：区分编辑器的dom节点。
 *disabled: 是否禁止输入  默认false
 *
 */

import { quillEditor, Quill } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import $config from '@/appConfig.js'
import axios from 'axios'
import Vue from 'vue'
// 这里引入修改过的video模块并注册
import Video from './video'
Quill.register(Video, true)
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // toggled buttons
  ['blockquote'],
  [
    {
      header: 1
    },
    {
      header: 2
    }
  ], // custom button values
  [
    {
      list: 'ordered'
    },
    {
      list: 'bullet'
    }
  ],
  [
    {
      script: 'sub'
    },
    {
      script: 'super'
    }
  ], // superscript/subscript
  [
    {
      indent: '-1'
    },
    {
      indent: '+1'
    }
  ], // outdent/indent
  [
    {
      direction: 'rtl'
    }
  ], // text direction
  [
    {
      size: ['small', false, 'large', 'huge']
    }
  ], // custom dropdown
  [
    {
      color: []
    },
    {
      background: []
    }
  ], // dropdown with defaults from theme
  [
    {
      header: [1, 2, 3, 4, 5, 6, false]
    }
  ],
  [
    {
      font: []
    }
  ],
  [
    {
      align: []
    }
  ],
  ['image', 'video'],
  ['clean'] // remove formatting button
]
export default {
  name: 'FuncFormsEdit',
  props: {
    heightMultiple: {
      type: Number,
      default: 1.5
    },
    height: {
      type: String,
      default: '200'
    },
    uploadUrl: {
      type: String
    },
    value: {
      type: String
    },
    quillIndex: {
      type: Number,
      default: 0
    },
    toref: {
      type: String,
      default: 'quillEditor'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 视频上传配置
    uploadVideoConfig: {
      type: Object,
      default () {
        return {
          uploadUrl: `${this.$config.SERVER_URL}/admin/sys/oss/upload`, // 上传地址
          maxSize: 50, // 图片上传大小限制，默认不超过2M
          name: 'Filedata', // 图片上传字段
          headers: {
            token: Vue.cookie.get('token'),
            'Content-Type': 'multipart/form-data'
          }
        }
      }
    }
  },
  components: {
    quillEditor
  },
  data () {
    return {
      content: '',
      editorOption: {
        placeholder: '',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            // 点击按钮选择本地图片
            handlers: {
              image: value => {
                if (value) {
                  let index = this.quillIndex
                  // 触发input框选择图片文件
                  document.querySelectorAll('.quill-img input')[index].click()
                } else {
                  this.quill.format('image', false)
                }
              },
              video: () => {
                // 覆盖默认的上传视频，点击视频图标，显示弹窗
                this.videoForm.show = true
              }
            }
          }
        }
      },
      // 视频上传变量
      videoForm: {
        show: false, // 显示插入视频链接弹框的标识
        videoLink: '',
        activeName: 'second'
      },
      loading: false, // 加载loading
    }
  },
  created () {
    this.content = this.value
  },
  watch: {
    value (n, o) {
      this.content = n
      // this.$refs[this.toref].quill.enable(false);//去掉焦点
      // // setTimeout(() => {
      // //   this.$refs[this.toref].quill.enable(true); //1秒之后可以点击（聚焦）
      // // }, 1000);
      //  this.$nextTick(()=>{
      //    this.$refs[this.toref].quill.enable(true)
      //  })
    }
  },
  methods: {
    beforeUpload () { },
    // 获得焦点事件
    onEditorFocus (event) {
      if (this.disabled) {
        event.enable(false)
      }
    },
    // 随机生成文件名
    random_string (len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    handleUploadForm (param) {
      let that = this

      let loading = that.$loading({
        lock: true,
        text: '上传中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      let formData = new FormData()
      formData.append('file', param.file)
      let config = {
        headers: {
          token: Vue.cookie.get('token'),
          'Content-Type': 'multipart/form-data'
        }
      }
      axios
        .post(
          `${this.$config.SERVER_URL}/admin/sys/oss/upload`,
          formData,
          config
        )
        .then(obj => {
          if (obj.status == 200) {
            let fileUrl = obj.data.data.url
            let quill = this.$refs[this.toref].quill
            let length = quill.getSelection().index // 获取光标所在位置
            quill.insertEmbed(length, 'image', fileUrl) // 插入资源  res.url为服务器返回的地址
            quill.setSelection(length + 1) // 调整光标到最后
          } else {
            this.$Message.error('图片插入失败')
          }
          loading.close()
        })

      // this.$post("file/upload", formData).then(res => {
      //   if (res.code === 0) { // 如果上传成功
      //     //let quill = this.$refs['myQuillEditor'].quill;// 获取富文本组件实例
      //     console.log(this.toref)
      //     let quill = this.$refs[this.toref].quill
      //     let length = quill.getSelection().index; // 获取光标所在位置

      //     quill.insertEmbed(length, "image", res.url); // 插入资源  res.url为服务器返回的地址
      //     quill.setSelection(length + 1); //调整光标到最后
      //   } else {
      //     this.$Message.error("图片插入失败");
      //   }

      //   loading.close()
      // })
    },
    uploadSuccess (res, file) { },
    getTxtchild () {
      this.$emit('getTxt', this.content)
    },
    hideLoading () {
      this.loading = false
    },
    /** --------- 视频上传相关 start ---------  */
    insertVideoLink (videoLink, poster) {
      if (!videoLink) return this.$message.error('视频地址不能为空！')
      this.videoForm.show = false
      let quill = this.$refs[this.toref].quill
      // 获取富文本
      let range = quill.getSelection()
      // 获取光标位置：当编辑器中没有输入文本时，这里获取到的 range 为 null
      let index = range ? range.index : 0
      // 没有视频默认封面时，设置默认视频封面图片
      const img = poster ? poster : videoLink + '?x-oss-process=video/snapshot,t_0,f_jpg'
      // 在光标所在位置 插入视频
      quill.insertEmbed(index, 'video', {
        url: videoLink,
        poster: img
      })
      // 调整光标到最后
      quill.setSelection(index + 1)
    },
    // el-文件上传组件
    onBeforeUploadVideo (file) {
      this.loading = true
      let acceptArr = ['video/mp4']
      const isVideo = acceptArr.includes(file.type)
      const isLt1M = file.size / 1024 / 1024 < this.uploadVideoConfig.maxSize
      if (!isVideo) {
        // this.hideLoading()
        this.$message.error('只能上传mp4格式文件!')
      }
      if (!isLt1M) {
        this.hideLoading()
        this.$message.error(`上传文件大小不能超过 ${this.uploadVideoConfig.maxSize}MB!`)
      }
      return isLt1M && isVideo
    },
    handleUploadVideoForm (param) {
      let that = this

      let loading = that.$loading({
        lock: true,
        text: '上传中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      let formData = new FormData()
      formData.append('file', param.file)
      let config = {
        headers: {
          token: Vue.cookie.get('token'),
          'Content-Type': 'multipart/form-data'
        }
      }
      axios
        .post(
          `${this.$config.SERVER_URL}/admin/sys/oss/upload`,
          formData,
          config
        )
        .then(obj => {
          if (obj.status == 200) {
            this.hideLoading()
            this.insertVideoLink(obj.data.data.url)
          } else {
            this.$Message.error('图片插入失败')
          }
          loading.close()
        })
    },
    // 文件上传成功时的钩子
    onSuccessVideo (res) {
      this.hideLoading()
      if (res.code === 200) {
        this.insertVideoLink(res.url)
      } else {
        this.$Message.error('图片插入失败')
      }
    },
    // 文件上传失败时的钩子
    onErrorVideo () {
      this.hideLoading()
      this.$message.error('上传失败')
    },
    /**--------- 视频上传相关 end --------- */
  }
}
</script>

<style scoped>
.quill-editor {
  line-height: normal;
}

.ivu-upload {
  display: none;
}

.el-upload-list,
ul {
  display: none !important;
}

em {
  font-style: italic !important;
}

.card>>>.ql-container {
  height: 78% !important;
}
</style>
